<template autoRoute="true">
  <div class="field-container">
    <section class="nav">
      <div class="left">
        <div>任务字段模版</div>
        <div>
          任务字段管理用于配置任务需要的显示字段，配置完成后需和任务类型进行关联，配置后对后续使用该任务类型的任务生效。
        </div>
      </div>
      <div class="right">
        <img src="@/assets/pm/taskFieldTemplateNav.png" />
      </div>
    </section>
    <section class="top">
      <div class="title">任务字段模版管理</div>
      <div style="display: flex; gap: 12px">
        <el-input
          v-model="input2"
          class="responsive-input"
          placeholder="请输入关键词搜索"
          :prefix-icon="Search"
        />
        <el-button type="primary" :icon="Plus">添加</el-button>
      </div>
    </section>
    <div ref="memberTableRef" class="table-container"></div>

    <!-- 字段配置悬浮层 -->
    <FieldConfigPopup
      :fields="currentFields"
      :position="fieldConfigPosition"
      :visible="showFieldConfig"
      @close="showFieldConfig = false"
    />
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, ref } from "vue";
  import { Plus, Search } from "@element-plus/icons-vue";
  import * as VTable from "@visactor/vtable";
  import { settingIcon } from "@/utils/SvgIcons";
  import { useRoute, useRouter } from "vue-router";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import { usePMGlobalSettingStore } from "@/stores/pmGlobalSetting.ts";
  const pmGlobalSettingStore = usePMGlobalSettingStore();

  const input2 = ref("");

  const router = useRouter();
  const route = useRoute();
  // 容器引用
  const memberTableRef = ref<HTMLDivElement | null>(null);

  const initTable = () => {
    if (!memberTableRef.value) {
      return;
    }

    VTable.register.icon("config-button", {
      type: "text",
      content: "配置字段",
      name: "config-button",
      positionType: VTable.TYPES.IconPosition.left,
      style: {
        fill: "#1AA1FB",
        cursor: "pointer",
        underline: 0,
        fontSize: 14,
        marginRight: 8,
      },
    });

    VTable.register.icon("edit-button", {
      type: "text",
      content: "编辑",
      name: "remove-button",
      positionType: VTable.TYPES.IconPosition.left,
      style: {
        fill: "#1AA1FB",
        cursor: "pointer",
        underline: 0,
        fontSize: 14,
        marginRight: 8,
      },
    });

    VTable.register.icon("del-button", {
      type: "text",
      content: "删除",
      name: "remove-button",
      positionType: VTable.TYPES.IconPosition.left,
      style: {
        fill: "#1AA1FB",
        cursor: "pointer",
        underline: 0,
        fontSize: 14,
        marginRight: 8,
      },
    });

    const option = {
      columns: [
        {
          field: "Order ID",
          title: "成员",
          width: "auto",
        },
        {
          field: "Customer ID",
          title: "角色",
          width: "auto",
        },
        {
          id: 999,
          field: "operations",
          type: "string",
          icon: ["config-button", "edit-button", "del-button"],
          headerIcon: [
            {
              type: "text",
              name: "operation-text",
              content: "操作", // 添加content属性
              positionType: VTable.TYPES.IconPosition.left, // 文字在左边
              style: {
                fontSize: 12,
                fill: "#999999",
                underline: 0,
              },
              cursor: "pointer",
            },
            {
              type: "svg",
              name: "settingIcon",
              positionType: VTable.TYPES.IconPosition.right, // 图标在右边
              width: 14,
              height: 14,
              marginRight: 8, // 右边距
              svg: settingIcon,
              cursor: "pointer",
            },
          ],
        },
      ],
      records: [
        {
          "Order ID": "1",
          "Customer ID": "1",
        },
        {
          "Order ID": "1",
          "Customer ID": "1",
        },
      ],
      autoFillWidth: true,

      // 边框显示配置
      border: {
        showRowBorder: true, // 显示行边框（横向）
        showColumnBorder: false, // 隐藏列边框（纵向）
      },

      // 主题配置
      theme: {
        // 去除外边框
        outerBorder: {
          lineWidth: 0, // 外边框宽度设为0
          color: "transparent", // 外边框颜色透明
        },

        // 表头样式
        headerStyle: {
          borderColor: "#e6e6e6",
          fontSize: 12,
          color: "#999999",
          // 表头只显示底部边框
          borderLineWidth: [0, 0, 1, 0], // [上, 右, 下, 左] 边框宽度
        },

        // 身体样式
        bodyStyle: {
          borderColor: "#e6e6e6",
          fontSize: 14,
          // 身体单元格只显示底部边框
          borderLineWidth: [1, 0, 1, 0], // [上, 右, 下, 左] 边框宽度
        },
      },
    };
    const tableInstance = new VTable.ListTable(memberTableRef.value, option);

    tableInstance.on("click_cell", (args: any) => {
      const { targetIcon, col, row, field } = args;
      if (targetIcon) {
        if (targetIcon.name === "config-button") {
          router.push({
            path: "/pm/globalSetting/taskFieldTemplateDetail",
            query: {
              projectId: route.query.projectId,
            },
          });
          pmGlobalSettingStore.toggleBreadcrumbStatus(false);
        }
        if (targetIcon.name === "settingIcon") {
          const tableRect = memberTableRef.value?.getBoundingClientRect();
          const iconPosition = {
            left: (tableRect?.right || 0) - 50,
            top: (tableRect?.top || 0) - 40,
          };

          const popupPosition = {
            left: iconPosition.left - 240,
            top: iconPosition.top,
          };
          if (showFieldConfigPopup) {
            showFieldConfigPopup(
              popupPosition,
              option.columns
                .filter((j) => j.field !== "operations")
                .map((item) => {
                  return {
                    ...item,
                    name: item.title,
                    invisible: true,
                  };
                }),
            );
          }
        }
      }
    });
  };

  // 字段配置弹窗相关状态
  const showFieldConfig = ref(false);

  const currentFields = ref<any[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });

  // 显示字段配置弹窗
  const showFieldConfigPopup = (
    position: { left: number; top: number },
    fields,
  ) => {
    console.log("fields", fields);
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };

  onMounted(() => {
    nextTick(() => {
      initTable();
      pmGlobalSettingStore.toggleBreadcrumbStatus(true);
    });
  });
</script>

<style scoped lang="scss">
  .table-container {
    margin-top: 12px;
    height: calc(100vh - 180px);
  }

  .field-container {
    padding: 16px;
  }
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-weight: 500;
      font-size: 18px;
      line-height: 22px;
    }
  }

  .nav {
    margin-bottom: 12px;
    background-color: #edf2ff;
    padding: 12px 18px;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    .left {
      & > div:first-child {
        font-size: 24px;
        color: #141414;
        margin: 5px 0;
      }
      & > div:last-child {
        font-size: 14px;
        color: #5e5e5e;
        margin: 2px 0;
      }
    }
    .right {
      img {
        height: 65px;
      }
    }
  }
</style>
